package com.cx.interact.client.admin.dao.act;

import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.stereotype.Repository;

import com.cx.base.apiModel.PageModel;
import com.cx.base.dao.AbstractBaseDao;
import com.cx.base.utils.IntegerUtil;
import com.cx.base.utils.StringUtil;
import com.cx.interact.client.admin.dto.act.ActTemplateDTO;
import com.cx.interact.client.admin.dto.act.StorageDTO;

@Repository
public class StorageDAO extends AbstractBaseDao{

	
	/**
	 * 更新
	 * */
	public StorageDTO saveOrUpdateActStorage( Integer actId, String storageKey, String storageValue){
		if(actId > 0 && StringUtil.isNotNull(storageKey)){
			Integer remainder = IntegerUtil.getTwentyRemainder(actId);
			
			//判断是否存在
			String querySql = " select count(1) as num from iat_storage_"+remainder+" where act_id = ? and storage_key = ? ";
			Long l = 0L;
			try {
				l = jdbcTemplate.queryForLong(querySql, actId,storageKey);
			} catch (Exception e) {
			}
			
			//更新数据
			if(l > 0){
				String sql = " update iat_storage_"+remainder+" set storage_value = ? where act_id = ? and storage_key = ? ";
				jdbcTemplate.update(sql,storageValue,actId,storageKey);
			}else{
				String sql = " insert into iat_storage_"+remainder+"(act_id,storage_key,storage_value) VALUES(?,?,?) ";
				jdbcTemplate.update(sql,actId,storageKey,storageValue);
			}
		}
		
		//返回
		StorageDTO dto = new StorageDTO();
		dto.setActId(actId);
		dto.setStorageKey(storageKey);
		dto.setStorageValue(storageValue);
		
		return dto;
	}
	
	/**
	 * 精确查询
	 * */
	public StorageDTO getActStorage(Integer actId, String storageKey){
		if(actId > 0 && StringUtil.isNotNull(storageKey)){
			Integer remainder = IntegerUtil.getTwentyRemainder(actId);
			
			String sql = " select * from iat_storage_"+remainder+" where act_id = ? and storage_key = ? ";
			
			List<Object> parameter = new ArrayList<Object>();
			parameter.add(actId);
			parameter.add(storageKey);
			
			PageModel<StorageDTO> pageModel = getPageList(1, 1, sql, parameter.toArray(), ParameterizedBeanPropertyRowMapper.newInstance(StorageDTO.class));
			if(pageModel != null && pageModel.getItems().size() > 0){
				return pageModel.getItems().get(0);
			}
		}
		return null;
	}
	
	/**
	 * 查询活动所有
	 * */
	public PageModel getActStorages(Integer actId){
		if(actId > 0){
			Integer remainder = IntegerUtil.getTwentyRemainder(actId);
			
			String sql = " select * from iat_storage_"+remainder+" where act_id = ? ";
			
			List<Object> parameter = new ArrayList<Object>();
			parameter.add(actId);
			
			PageModel<ActTemplateDTO> pageModel = getPageList(1, 5000, sql, parameter.toArray(), ParameterizedBeanPropertyRowMapper.newInstance(ActTemplateDTO.class));
			
			return pageModel;
		}
		return new PageModel();
	}
}
